package com.gutetec.cms.bmc.wrapper;

import java.util.HashMap;
import java.util.List;

import javax.ws.rs.core.Response;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gutetec.cms.bmc.bean.AlarmInfo;
import com.gutetec.cms.bmc.db.dao.AlarmDao;
import com.gutetec.cms.bmc.db.dbUtil.FmDBUtil;

import net.sf.json.JSONObject;

public class AlarmWrapper {
private static final Logger LOGGER = LoggerFactory.getLogger(AlarmWrapper.class);
	
	/**
	 * find active alarm by page
	 * 
	 * @param paramMap
	 * @return
	 */
	public static Response findActiveAlarmByPage(HashMap<String, Object> paramMap) {
		AlarmDao dao = (AlarmDao) FmDBUtil.getDaoInstance("AlarmInfo");
		List<AlarmInfo> result = null;
		int totalRows = 0;
		try {
			result = dao.findActiveAlarmByPage(paramMap);
			totalRows = dao.getActiveAlarmNum();
		} catch (HibernateException e) {
			LOGGER.error("error is" + e.getMessage());
			return Response.serverError().build();
		}

		JSONObject object = new JSONObject();
		if (0 == totalRows) {
			object.put("total", totalRows);
			object.put("rows", "[]");
			return Response.ok(object).build();
		} else {
			object.put("total", totalRows);
			object.put("rows", result);
			return Response.ok(object).build();
		}
	}
	
	/**
	 * find history alarm  by page
	 * 
	 * @param paramMap
	 * @return
	 */
	public static Response findByPage(HashMap<String, Object> paramMap) {
		AlarmDao dao = (AlarmDao) FmDBUtil.getDaoInstance("AlarmInfo");
		List<AlarmInfo> result = null;
		int totalRows = 0;
		try {
			result = dao.findHistoryAlarmByPage(paramMap);
			totalRows = dao.getHistoryAlarmNum();
		} catch (HibernateException e) {
			LOGGER.error("error is" + e.getMessage());
			return Response.serverError().build();
		}

		JSONObject object = new JSONObject();
		if (0 == totalRows) {
			object.put("total", totalRows);
			object.put("rows", "[]");
			return Response.ok(object).build();
		} else {
			object.put("total", totalRows);
			object.put("rows", result);
			return Response.ok(object).build();
		}
	}
	
	/**
	 * delete alarm by id
	 * 
	 * @param id
	 * @return
	 */
	public static Response deleteAlarm(String id) {
		JSONObject result = new JSONObject();
		try {
			AlarmDao dao = (AlarmDao) FmDBUtil.getDaoInstance("AlarmInfo");
			dao.deleteById(id);
		} catch (Exception e) {
			LOGGER.error("del alarm fail.", e);
			result.put("result", "-1");
			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build();
		}
		result.put("result", "0");
		return Response.status(Response.Status.OK).entity(result).build();
	}
}
